﻿using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Data.SqlClient;

namespace WeatherComm
{
    public class RootData
    {
        public string message { get; set; }
        public int status { get; set; }
        public string date { get; set; }
        public string time { get; set; }
        public Cityinfo cityInfo { get; set; }
        public Data data { get; set; }

        public static RootData GetDataFromNet(string url)
        {
            var httpStr = HttpHelper.GetUrl2Html(url, "UTF-8");
            var data = JsonConvert.DeserializeObject<RootData>(httpStr);
            return data;
        }
        public static bool Write2Db(RootData value)
        {
            var connectString = ConfigurationManager.AppSettings["Connection"];
            try
            {
                //var high = Convert.ToSingle(value.data.forecast[0].high.Split(' ')[1].Split('℃')[0]);
                //var low = Convert.ToSingle(value.data.forecast[0].low.Split(' ')[1].Split('℃')[0]);
                var sql =
                    $@"INSERT INTO [dbo].[WeatherData]
                    ([City]
                    ,[High]
                    ,[Low]
                    ,[RecDate])
                     VALUES
                     ('{value.cityInfo.city}'
                    ,{value.data.forecast[0].high}
                    ,{value.data.forecast[0].low}
                    ,'{value.time}')";

                using (var conn = new SqlConnection(connectString))
                {
                    conn.Open();
                    var cmd = new SqlCommand(sql, conn);
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    cmd.Dispose();
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

    }
}